package com.guoji.cameracall.socket

import android.util.Log
import org.java_websocket.WebSocket
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.handshake.ServerHandshake
import org.java_websocket.server.WebSocketServer
import java.lang.Exception
import java.net.InetSocketAddress
import java.net.URI
import java.nio.ByteBuffer

/**
 * create by zhongZihao on 2021/9/27
 */
class SocketLiveServer(private val port: Int) : ISocketLive {
    private var myWebSocketServer: MyWebSocketServer? = null
    private var websocket: WebSocket? = null
    private var socketCallback: ((data: ByteArray?) -> Unit)? = null


    inner class MyWebSocketServer(address: InetSocketAddress) : WebSocketServer(address) {
        override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) {
            websocket = conn
            Log.d("TAG_SocketLive", "SocketLiveServer open ....$address")

        }

        override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {
        }

        override fun onMessage(conn: WebSocket?, message: String?) {
        }

        override fun onMessage(conn: WebSocket?, buf: ByteBuffer) {
            val bytes = ByteArray(buf.remaining())
            buf.get(bytes)
            socketCallback?.invoke(bytes)
        }

        override fun onError(conn: WebSocket?, ex: Exception?) {
        }

        override fun onStart() {
        }
    }

    override fun start() {
        try {
            myWebSocketServer = MyWebSocketServer(InetSocketAddress(port))
            myWebSocketServer!!.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun setDataCallback(socketCallback: (data: ByteArray?) -> Unit) {
        this.socketCallback = socketCallback
    }

    override fun sendData(byteArray: ByteArray) {
        if (websocket?.isOpen == true) {
            websocket!!.send(byteArray)
        }
    }

    override fun close() {
        try {
            websocket?.close()
            myWebSocketServer?.stop()
            myWebSocketServer = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}